package com.min.generator.controller;

import cn.hutool.core.io.IoUtil;
import com.min.common.entity.R;
import com.min.common.util.GsonUtil;
import com.min.generator.service.GeneratorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author fengt
 */
@RestController
public class GeneratorController {

    @Autowired
    private GeneratorService service;

    /**
     * 查询数据库中所有表
     * @return: com.min.common.entity.R
     * @author: fengt
     * @date: 2021/3/21 12:03
     **/
    @ResponseBody
    @RequestMapping("/tables")
    public R tables(){
        return R.ok().put("tables", service.list());
    }

    /**
     * 生成zip文件前端下载
     * @param tables:
     * @param response:
     * @return: void
     * @author: fengt
     * @date: 2021/3/21 12:03
     **/
    @PostMapping("/generate/zip")
    public void generateZip(@RequestBody List<String> tables, HttpServletResponse response) throws IOException {

        byte[] data = service.makeZip(tables);

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"GeneratorTableCode.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IoUtil.write(response.getOutputStream(), true, data);
    }

    /**
     * 直接在配置的mainPath目录下生成文件
     * @param tables:
     * @return: void
     * @author: fengt
     * @date: 2021/3/21 12:04
     **/
    @PostMapping("/generate/file")
    public R generateFile(@RequestBody List<String> tables) {

        if (null == tables || tables.isEmpty()) {
            return R.error("参数错误");
        }

        service.makeFile(tables);

        return R.ok();
    }


}
